const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

// 测试配置
const BASE_URL = 'http://localhost:3000';
const API_BASE = `${BASE_URL}/api/data`;

// 测试数据
const testData = {
  uploadTime: '2024-01-15 14:30:00',
  hallName: '测试厅',
  hostName: '测试主持人',
  dataValue: '1000.50',
  headDataValue: '500.25',
  hostHall: '测试主持人-测试厅'
};

// 创建测试图片文件
function createTestImage(filename) {
  const testImagePath = path.join(__dirname, filename);
  // 创建一个简单的测试图片（1x1像素的PNG）
  const pngBuffer = Buffer.from([
    0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D,
    0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
    0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xDE, 0x00, 0x00, 0x00,
    0x0C, 0x49, 0x44, 0x41, 0x54, 0x08, 0x99, 0x01, 0x01, 0x00, 0x00, 0x00,
    0xFF, 0xFF, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xE2, 0x21, 0xBC, 0x33,
    0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82
  ]);
  fs.writeFileSync(testImagePath, pngBuffer);
  return testImagePath;
}

// 测试单条数据上传
async function testSingleUpload() {
  console.log('\n=== 测试单条数据上传 ===');
  
  try {
    // 创建测试图片
    const dataScreenshotPath = createTestImage('test-data-screenshot.png');
    const headScreenshotPath = createTestImage('test-head-screenshot.png');
    
    const formData = new FormData();
    
    // 添加文本数据
    Object.keys(testData).forEach(key => {
      formData.append(key, testData[key]);
    });
    
    // 添加图片文件
    formData.append('dataScreenshot', fs.createReadStream(dataScreenshotPath));
    formData.append('headDataScreenshot', fs.createReadStream(headScreenshotPath));
    
    const response = await axios.post(`${API_BASE}/upload`, formData, {
      headers: {
        ...formData.getHeaders(),
      },
      timeout: 10000
    });
    
    console.log('✅ 单条数据上传成功:', response.data);
    
    // 清理测试文件
    fs.unlinkSync(dataScreenshotPath);
    fs.unlinkSync(headScreenshotPath);
    
  } catch (error) {
    console.error('❌ 单条数据上传失败:', error.response?.data || error.message);
  }
}

// 测试Excel批量上传
async function testExcelUpload() {
  console.log('\n=== 测试Excel批量上传 ===');
  
  try {
    // 创建测试Excel文件
    const XLSX = require('xlsx');
    const testData = [
      {
        '上传时间': '2024-01-15 14:30:00',
        '厅名': '测试厅1',
        '主持人': '测试主持人1',
        '数据值': '1000.50',
        '大头数据值': '500.25',
        '主持-厅名': '测试主持人1-测试厅1'
      },
      {
        '上传时间': '2024-01-15 15:30:00',
        '厅名': '测试厅2',
        '主持人': '测试主持人2',
        '数据值': '2000.75',
        '大头数据值': '1000.50',
        '主持-厅名': '测试主持人2-测试厅2'
      }
    ];
    
    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.json_to_sheet(testData);
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    
    const excelPath = path.join(__dirname, 'test-data.xlsx');
    XLSX.writeFile(workbook, excelPath);
    
    const formData = new FormData();
    formData.append('excelFile', fs.createReadStream(excelPath));
    
    const response = await axios.post(`${API_BASE}/upload-excel`, formData, {
      headers: {
        ...formData.getHeaders(),
      },
      timeout: 10000
    });
    
    console.log('✅ Excel批量上传成功:', response.data);
    
    // 清理测试文件
    fs.unlinkSync(excelPath);
    
  } catch (error) {
    console.error('❌ Excel批量上传失败:', error.response?.data || error.message);
  }
}

// 测试厅名管理
async function testHallManagement() {
  console.log('\n=== 测试厅名管理 ===');
  
  try {
    // 添加厅名
    const addResponse = await axios.post(`${API_BASE}/halls`, {
      hallName: '测试厅'
    }, {
      headers: { 'Content-Type': 'application/json' },
      timeout: 5000
    });
    console.log('✅ 添加厅名成功:', addResponse.data);
    
    // 获取厅名列表
    const getResponse = await axios.get(`${API_BASE}/halls`, {
      timeout: 5000
    });
    console.log('✅ 获取厅名列表成功:', getResponse.data);
    
  } catch (error) {
    console.error('❌ 厅名管理测试失败:', error.response?.data || error.message);
  }
}

// 测试数据查询
async function testDataQuery() {
  console.log('\n=== 测试数据查询 ===');
  
  try {
    const response = await axios.get(`${API_BASE}/query`, {
      params: {
        startDate: '2024-01-01',
        endDate: '2024-12-31',
        page: 1,
        pageSize: 10
      },
      timeout: 5000
    });
    
    console.log('✅ 数据查询成功:', response.data);
    
  } catch (error) {
    console.error('❌ 数据查询失败:', error.response?.data || error.message);
  }
}

// 主测试函数
async function runTests() {
  console.log('🚀 开始测试上传接口...');
  console.log(`📡 服务器地址: ${BASE_URL}`);
  
  // 检查服务器是否运行
  try {
    await axios.get(`${BASE_URL}/api/data/halls`, { timeout: 3000 });
    console.log('✅ 服务器连接正常');
  } catch (error) {
    console.error('❌ 无法连接到服务器，请确保服务器正在运行');
    console.log('💡 请先运行: npm start 或 node app.js');
    return;
  }
  
  // 先添加测试厅名
  console.log('\n=== 添加测试厅名 ===');
  try {
    const testHalls = ['测试厅', '测试厅1', '测试厅2'];
    for (const hallName of testHalls) {
      await axios.post(`${API_BASE}/halls`, {
        hallName: hallName
      }, {
        headers: { 'Content-Type': 'application/json' },
        timeout: 5000
      });
      console.log(`✅ 添加厅名成功: ${hallName}`);
    }
  } catch (error) {
    console.log('⚠️ 厅名可能已存在，继续测试...');
  }
  
  // 运行测试
  await testHallManagement();
  await testSingleUpload();
  await testExcelUpload();
  await testDataQuery();
  
  console.log('\n🎉 测试完成！');
}

// 运行测试
if (require.main === module) {
  runTests().catch(console.error);
}

module.exports = { runTests }; 